﻿using System;
using System.Collections.Generic;
using System.Text;

namespace JSONUtil
{
    internal class JSONTextReader
    {
        public static readonly char EmptyChar = (char)0;

        StringBuilder sb = null;
        int position = 0;

        public JSONTextReader(string text)
        {
   
            sb = new StringBuilder(text);
        }

        public string Text
        {
            get
            {
                return sb.ToString();
            }
        }

        public int Position
        {
            get
            {
                return position;
            }
            set
            {
                position = value;
            }
        }

        public char Read(bool failIfEnded)
        {
            if (position < sb.Length)
                return sb[position++];
            else
                throw new InvalidOperationException("No further characters can be read!");
        }

        public char Read()
        {
            return Read(true);
        }

        public char Peek()
        {
            if (position < sb.Length)
                return sb[position];
            else
                return EmptyChar;
        }


        public void SkipWhiteSpaces()
        {
            while (true)
            {
                char i = Read();
                if (i == JSONTextReader.EmptyChar)
                    return;
                else if (i == ' ' || i == '\n' || i == '\r' || i == '\t')
                    continue;
                else
                {
                    position--;
                    return;
                }
            }
        }

        public bool SkipTill(char charToSkipTill)
        {
            while (true)
            {
                char i = Read();
                if (i == JSONTextReader.EmptyChar)
                    return false;
                else if (i == charToSkipTill)
                    return true;
            }
            position--;
            return false;
        }

        public string ReadUntil(char charToReadTill)
        {
            StringBuilder sb = new StringBuilder();
            bool lastCharIsEscapingChar = false;
            while (true)
            {
                char i = Read();
                if (i == JSONTextReader.EmptyChar)
                    return null;
                if (i == '\\')
                {
                    lastCharIsEscapingChar = true;
                    sb.Append(i);
                }
                else if (!lastCharIsEscapingChar && i == charToReadTill)
                    break;
                else
                {
                    lastCharIsEscapingChar = false;
                    sb.Append(i);
                }
            }
            return sb.ToString();
        }
    }
}
